ตัวอย่างโค้ดในภาษา Python ของ อาร์เอสเอ

โค้ดในส่วนของการสร้างคีย์

 1 import random 2 def is_prime(num): 3     if num == 2: 4         return True 5     if num < 2 or num % 2 == 0: 6         return False 7     for n in range(3, int(num ** 0.5) + 2, 2): 8         if num % n == 0: 9             return False10     return True11 12 def gcd(a, b):13     while b != 0:14         a, b = b, a % b15     return a16 '''Euclid's extended algorithm for finding the multiplicative inverse of two numbers'''17 def multiplicative_inverse(e, z):18     d = 019     x1 = 020     x2 = 121     y1 = 122     temp_z = z23 24     while e > 0:25         temp1 = temp_z // e26         temp2 = temp_z - temp1 * e27         temp_z = e28         e = temp229 30         x = x2 - temp1 * x131         y = d - temp1 * y132 33         x2 = x134         x1 = x35         d = y136         y1 = y37 38     if temp_z == 1:39         return d + z 40 41 def generate_keypair(p, q):42     if not (is_prime(p) and is_prime(q)):43         raise ValueError('Both numbers must be prime.')44     elif p == q:45         raise ValueError('p and q cannot be equal')46     n = p * q47     z = (p - 1) * (q - 1)48     e = random.randrange(1, n)49     g = gcd(e, z)50     while g != 1:51         e = random.randrange(1, n)52         g = gcd(e, z)53 54     d = multiplicative_inverse(e, z)55     return (e,n),(d,n)

โค้ดในส่วนของการเข้ารหัส

1 def encrypt(key,plainText):2     e, n = key3     cipherText = ""4     for i in range(len(plainText)):5         cipherText += chr(((ord(plainText[i]) ** e) % n))6     return cipherText

โค้ดในส่วนของการถอดรหัส

1 def decrypt(key, cipherText):2     d, n = key3     plainText = ""4     for i in range(len(cipherText)):5         plainText += chr(((ord(cipherText[i]) ** d) % n))6     return plainText
บทความเกี่ยวกับเทคโนโลยี หรือ สิ่งประดิษฐ์นี้ยังเป็นโครง คุณสามารถช่วยวิกิพีเดียได้โดยเพิ่มข้อมูล